"""
GUI 组件类
"""
import tkinter as tk
from tkinter import filedialog, messagebox
from utils.helpers import validate_file_path


class MenuForm(tk.Frame):
    """菜单表单组件"""

    def __init__(self, parent):
        super().__init__(parent, bg="#f0f0f0")
        self.create_widgets()

    def create_widgets(self):
        """创建表单组件"""
        # 菜单名称
        self.create_menu_name_field()

        # 命令路径
        self.create_command_field()

    def create_menu_name_field(self):
        """创建菜单名称输入字段"""
        label = tk.Label(self, text="菜单名称:", bg="#f0f0f0")
        label.pack(anchor="w", pady=(0, 5))

        self.entry_menu_name = tk.Entry(self, width=50)
        self.entry_menu_name.pack(fill=tk.X, pady=(0, 10))

    def create_command_field(self):
        """创建命令路径输入字段"""
        label = tk.Label(self, text="可执行文件路径:", bg="#f0f0f0")
        label.pack(anchor="w", pady=(0, 5))

        # 文件选择框架
        file_frame = tk.Frame(self, bg="#f0f0f0")
        file_frame.pack(fill=tk.X)

        self.entry_command = tk.Entry(file_frame, width=40)
        self.entry_command.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 5))

        browse_button = tk.Button(
            file_frame,
            text="浏览...",
            command=self.browse_file,
            width=8
        )
        browse_button.pack(side=tk.RIGHT)

    def browse_file(self):
        """打开文件选择对话框"""
        file_path = filedialog.askopenfilename(
            title="选择可执行文件",
            filetypes=[
                ("可执行文件", "*.exe"),
                ("批处理文件", "*.bat"),
                ("所有文件", "*.*")
            ]
        )
        if file_path:
            self.entry_command.delete(0, tk.END)
            self.entry_command.insert(0, file_path)

    def get_menu_name(self):
        """获取菜单名称"""
        return self.entry_menu_name.get().strip()

    def get_command_path(self):
        """获取命令路径"""
        return self.entry_command.get().strip()

    def clear_form(self):
        """清空表单"""
        self.entry_menu_name.delete(0, tk.END)
        self.entry_command.delete(0, tk.END)

    def validate_form(self):
        """验证表单数据"""
        menu_name = self.get_menu_name()
        command_path = self.get_command_path()

        if not menu_name:
            messagebox.showwarning("警告", "请输入菜单名称")
            return False

        if not command_path:
            messagebox.showwarning("警告", "请选择可执行文件")
            return False

        if not validate_file_path(command_path):
            messagebox.showwarning("警告", "选择的可执行文件不存在")
            return False

        return True


class ActionButtons(tk.Frame):
    """操作按钮组件"""

    def __init__(self, parent):
        super().__init__(parent, bg="#f0f0f0")
        self.callbacks = {}
        self.create_widgets()

    def create_widgets(self):
        """创建按钮组件"""
        # 添加按钮
        self.add_button = tk.Button(
            self,
            text="添加菜单",
            bg="#4CAF50",
            fg="white",
            width=12,
            command=self.on_add_click
        )
        self.add_button.pack(pady=5)

        # 删除按钮
        self.delete_button = tk.Button(
            self,
            text="删除菜单",
            bg="#f44336",
            fg="white",
            width=12,
            command=self.on_delete_click
        )
        self.delete_button.pack(pady=5)

    def set_callbacks(self, on_add=None, on_delete=None):
        """设置回调函数"""
        self.callbacks = {
            'on_add': on_add,
            'on_delete': on_delete
        }

    def on_add_click(self):
        """处理添加按钮点击"""
        if not hasattr(self, '_menu_form'):
            # 获取父容器中的菜单表单
            for widget in self.master.winfo_children():
                if isinstance(widget, MenuForm):
                    self._menu_form = widget
                    break

        if hasattr(self, '_menu_form') and self._menu_form.validate_form():
            menu_name = self._menu_form.get_menu_name()
            command_path = self._menu_form.get_command_path()

            if self.callbacks.get('on_add'):
                self.callbacks['on_add'](menu_name, command_path)

    def on_delete_click(self):
        """处理删除按钮点击"""
        if not hasattr(self, '_menu_form'):
            # 获取父容器中的菜单表单
            for widget in self.master.winfo_children():
                if isinstance(widget, MenuForm):
                    self._menu_form = widget
                    break

        if hasattr(self, '_menu_form'):
            menu_name = self._menu_form.get_menu_name()

            if not menu_name:
                messagebox.showwarning("警告", "请输入要删除的菜单名称")
                return

            if messagebox.askyesno("确认删除", f"确定要删除菜单 '{menu_name}' 吗？"):
                if self.callbacks.get('on_delete'):
                    self.callbacks['on_delete'](menu_name)